package com.startup.yellocar.component;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.startup.yellocar.dto.MessageDTO;

@Component
public class MailService {

	
	Logger log = Logger.getLogger(this.getClass());
	public void sendMail(MessageDTO messageDTO) throws Exception{
		 Properties props = new Properties();
			
	        try
	        {	
	            props.load(getClass().getResourceAsStream("mail.properties"));
	        }
	        catch(Exception e)
	        {
	          throw  new Exception("Can not load mail.properties",e);
	        }
	        final String username = props.getProperty("mail.username");
	        final String password = props.getProperty("mail.password");
	        Session session = Session.getInstance(props,
			  new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			  });
	        try{
	         // Create a default MimeMessage object.
	         MimeMessage message = new MimeMessage(session);

	         // Set From: header field of the header.
	         message.setFrom(new InternetAddress(messageDTO.getFrom()));

	         // Set To: header field of the header.
	         message.addRecipient(Message.RecipientType.TO,new InternetAddress(messageDTO.getTo()));
	         
	      // Set To: header field of the header.
	         message.addRecipient(Message.RecipientType.CC,new InternetAddress(messageDTO.getCc()));
	         
	      // Set To: header field of the header.
	         message.addRecipient(Message.RecipientType.BCC,new InternetAddress(messageDTO.getBcc()));

	         
	         // Set Subject: header field
	         message.setSubject(messageDTO.getSubject());

	         // Send the actual HTML message, as big as you like
	         message.setContent(messageDTO.getContent(),"text/html");

	         // Send message
	         Transport.send(message);
	         log.info("Sent message successfully....");
	      }catch (MessagingException mex) {
	    	  throw new Exception(mex.getLocalizedMessage(),mex);
	      }
	        
	}
}
